package com.fqr;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public abstract class FlexJob implements Runnable {

	private String name;
	
	private ErrorHandler errorHandler;

	public ErrorHandler getErrorHandler() {
		return errorHandler;
	}

	public void setErrorHandler(ErrorHandler errorHandler) {
		this.errorHandler = errorHandler;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Object getData() {
		return GlobalContext.get(Thread.currentThread().getId() + "." + name);
	}

	private List<String> dependsOn = new ArrayList<String>();

	public List<String> getDependsOn() {
		return dependsOn;
	}

	public void run() {
		runAllDependencies();
		try {
			runJob();
		} catch (Exception e) {
			errorHandler.handle(name, e);
		}
	}

	public abstract void runJob() throws Exception;

	public void runAllDependencies() {
		Logger logger = Logger.getLogger(getName());
		try {
			FlexSchedule schedule = FlexSchedule.getSchedule();
			for (String name : getDependsOn()) {
				schedule.runJob(name, null);
			}
		} catch (Exception e) {
			logger.warn("Error running dependent job", e);
		}
	}

}
